/**
 * show message
 */
function showMsg(message) {
	uni.showToast({
		title: message,
		icon: 'none'
	})
}

function showSuccess(message, calback) {
	uni.showToast({
		title: message,
		icon: 'success',
		duration: 2000
	});
	const timeout = setTimeout(() => {
		if (calback) calback();
		clearTimeout(timeout);
	}, 2000);
}

/**
 * 跳转去登录页面
 */
function toLoginPage(isRedirect = false) {
	if (isRedirect) uni.redirectTo({
		url: '/pages/public/login'
	});
	else uni.navigateTo({
		url: '/pages/public/login'
	});
}

/**
 * http
 */
const host_http = 'http://test.gsjpxt.top/jbkqbx/ajax.do?'

function request(url, data = {}, method = 'post', options = {
	login: false
}) {
	return new Promise((resolve, reject) => {
		var authPara='';
		if (options.login) {
			const token = wx.getStorageSync('token');			
			if (!token) {
				reject(toLoginPage);
				return false;
			}
			authPara='&token='+token+'&platform=android'
		}
		const obj = {
			url: host_http + url+authPara,
			header: {
				'Content-Type': 'application/json',
			},
			data: data,
			method: String(method).toUpperCase(),
			success: res => {
				if (res.statusCode == 403)
				{
					uni.navigateTo({
						url: '/pages/public/login'
					});
				}
				else resolve(res.data);
			},
			fail: res => {
				reject();
			}
		};		
		uni.request(obj);
	});
}

function formatNumber(number = '0') {
	const n = parseInt(number)
	return n < 10 ? `0${n}` : String(n)
}


function formatTime(date = Date.now()) {
	const d = new Date(date);
	return `${d.getYear()}-${formatNumber(d.getMonth()+1)}-${formatNumber(d.getDate())} ${formatNumber(d.getHours())}:${formatNumber(d.getMinutes())}`
}

/**
 * 检查
 */
function checked(type, data = '') {
	let check = false;
	switch (type) {
		case 'phone':
			check = /^1[0-9]{10,10}$/.test(data);
			break;
		case 'code':
			check = /^[0-9]{6}$/.test(data);
			break;
		default:
			break;
	}
	return check;
}


module.exports = {
	showSuccess,
	showMsg,
	request,
	checked,
	toLoginPage,
	formatTime
}
